package formal.array;

import java.util.Arrays;

/**
 * @author DengYuan2
 * @create 2021-02-04 20:39
 */
public class E_566 {
    public static void main(String[] args) {
        int[][] nums = {{1, 2}, {3, 4}};
        int[][] res = matrixReshape2(nums, 1, 4);
        for (int i = 0; i < res.length; i++) {
            System.out.println(Arrays.toString(res[i]));
        }

    }

    /**
     * 我的写法-虽然可以，但简直是多此一举，为啥要从1开始，还判断==0？太傻了
     *
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape(int[][] nums, int r, int c) {
        int row = nums.length;
        int col = nums[0].length;
        int count = row * col;
        if (c * r != count) {
            return nums;
        }
        int[][] res = new int[r][c];
        for (int i = 1; i <= count; i++) {
            int l1 = i / col;
            int h1 = i % col - 1;
            if (i % col == 0) {
                l1 -= 1;
                h1 = col - 1;
            }
            int l2 = i / c;
            int h2 = i % c - 1;
            if (i % c == 0) {
                l2 -= 1;
                h2 = c - 1;
            }
            res[l2][h2] = nums[l1][h1];
        }
        return res;
    }

    /**
     * 大神的写法
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape2(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }
        int[][] res = new int[r][c];
        //大神是这么写的，我觉得也可以像下面那么写
//        int idx =0;
//        for (int i = 0; i < r; i++) {
//            for (int j = 0; j < c; j++) {
//                res[i][j]=nums[idx/n][idx%n];
//                idx++;
//            }
//        }
        for (int i = 0; i < m * n; i++) {
            res[i / c][i % c] = nums[i / n][i % n];
        }
        return res;
    }

    /**
     * 官方-很巧妙，不用/或%
     * @param nums
     * @param r
     * @param c
     * @return
     */
    public static int[][] matrixReshape3(int[][] nums, int r, int c) {
        int m = nums.length;
        int n = nums[0].length;
        if (m * n != r * c) {
            return nums;
        }
        int[][] res = new int[r][c];
        int row = 0, col = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                res[row][col]=res[i][j];
                col++;
                if (col==n){
                    col=0;
                    row++;
                }
            }
        }
        return res;
    }
}
